<template>
  <div class="materielList">
    <jc-button
      :btn-arr="['reload', bomCost('unit:save') && 'newy', 'remove', 'option', 'sub', 'pass']"
      :disab-arr="['close', 'copy', 'cancel', 'com1', 'com2', 'chart', 'freeze']"
      @refresh="getMaterialList"
      @newly="addMateril"
      @audit="auditer(1)"
      @noAudit="auditer(2)"
      @submit="materSub(1)"
      @noSubmit="materSub(2)"
      @forbidden="using(1)"
      @startUsing="using(2)"
      @del="deleteMater"
      @toExcel="handleExport"
    />
    <div class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :search-son="searchSon"
          :msg="tacitly"
          @seek="collect"
          @hand="searchMaterialList"
        />
        <el-button
          type="primary"
          size="mini"
          class="btn"
          @click="searchMaterialList"
        >
          {{ $t('btn.search') }}
        </el-button>
        <filtration
          class="btn_spacing"
          :ftype="ftype"
          :msg="tacitly"
          :table-header="tableHeader1"
          :detail-header="materialTableHeader"
          :select-data="selectData"
          @seachData="searchMaterialList"
        />
      </div>
    </div>
    <div class="mainPage">
      <div class="left-mainPage">
        <el-tree
          ref="my-tree"
          node-key="funitgroupid"
          :data="materialGroupL"
          :props="defaultProps"
          :current-node-key="currentNodeKey"
          :default-expanded-keys="[0]"
          accordion
          @node-click="handleNodeClick"
        />
      </div>
      <div class="right-mainPage">
        <jc-table
          :table-header="materialTableHeader"
          :table-data="materialTableData"
          :table-height="tableHeight"
          sortable
          table-selection
          @selectionChange="selectionData"
          @clickRow="jumpMateriel"
        >
          <template v-slot:orderSlot="col">
            <el-link type="primary" @click="jumpMateriel(col.scope.row)">
              {{ col.scope.row.fnumber }}
            </el-link>
          </template>
          <!--基准计量单位-->
          <template v-slot:btnStates="col">
            <el-checkbox v-model="col.scope.row.fisbaseunit" disabled />
          </template>
          <!--审核状态-->
          <template v-slot:btnState="col">
            <el-tag
              :type="col.scope.row.stateColor"
            >
              {{ col.scope.row.fdocumentstatus }}
            </el-tag>
          </template>
          <!--禁用状态-->
          <template v-slot:tagSlot="clo">
            <el-tag v-if="clo.scope.row.fforbidstatus === 'A'">
              {{ $t('market.no') }}<!--否-->
            </el-tag>
            <el-tag v-else type="danger">
              {{ $t('market.yes') }}<!--是-->
            </el-tag>
          </template>
        </jc-table>
        <div class="footer">
          <jc-pagination
            :total="total"
            :page.sync="pagination.pageNum"
            :limit.sync="pagination.pageSize"
            @pagination="getMaterialList"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import jcButton from '@/components/Button'
import search from '@/components/Search'
import searData from '@/components/Search/mixin'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'
import filtration from '@/components/filtration'
import { Disable, toMxBmina } from '@/components/ToMxamineState'
import {
  deleteUnits,
  queryUnitGroupList,
  queryUnitList,
  unitsAudit, unitsDisable,
  unitsSubmit, unitsUnAudit, unitsUnDisable,
  unitsUnSubmit
} from '@/api/basicManagement/measuring'
export default {
  name: 'MeasurList',
  components: {
    jcButton,
    search,
    filtration
  },
  mixins: [searData],
  data() {
    return {
      ftype: 0,
      fbillNo: 'fnumber', // 产品描述
      materialGroupL: [
        {
          fname: this.$t('market.all'),
          funitgroupid: 0,
          details: []
        }
      ], // tree组数据
      currentNodeKey: '',
      loading: false,
      pagination: {
        pageNum: 1, // 当前页
        pageSize: 200 // 每页显示多少条数据
      },
      delArr: [],
      total: 0, // 总条目
      materialTableHeader: [
        { label: this.$t('shop.fnumber'), type: 'order', prop: 'fnumber', width: '120' },
        { label: this.$t('shop.name1'), prop: 'fname' },
        { label: this.$t('market.unitGroup'), prop: 'funitgroup' },
        { label: this.$t('market.precision'), prop: 'fprecision', width: '80' },
        { label: this.$t('market.isbaseunit'), type: 'states', prop: 'fisbaseunit', width: '120' },
        { label: this.$t('market.destunit'), prop: 'fdestunit', width: '100' },
        { label: this.$t('market.molecule'), prop: 'fconvertnumerator', width: '80' },
        { label: this.$t('market.currentunit'), prop: 'fcurrentunit', width: '100' },
        { label: this.$t('market.matrixing'), prop: 'fconvertdenominator', width: '80' },
        { label: this.$t('market.documentstatus'), type: 'state', prop: 'fdocumentstatus' },
        { label: this.$t('market.forbidStatu'), type: 'tag', prop: 'fforbidstatus' },
        { label: this.$t('market.note'), prop: 'fdescription', width: '200px' }
        // { label: this.$t('market.handle'), type: 'btn', minWidth: '80px' }
      ], // 表头数据
      materialTableData: [], // 表格数据
      defaultProps: {
        children: 'details',
        label: 'fname'
      },
      tableHeight: '75vh',
      tableHeader1: [
        { label: this.$t('market.createDate'), prop: 'fcreateDate' }
      ]
    }
  },
  created() {
    this.getMaterialGroupL()
    this.getMaterialList()
    this.tableHeader1 = this.materialTableHeader.concat(this.tableHeader1)
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 230px)' : '73vh'
  },
  methods: {
    // 导出表格
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.materialTableHeader.map(res => {
          return res.label
        })
        const filterVal = this.materialTableHeader.map(res => {
          return res.prop
        })
        if (this.materialTableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else {
          queryUnitList({
            pageSize: 100000,
            pageNum: 1,
            search: this.searCollData,
            fnumberGroup: this.currentNodeKey
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.array.map(res => {
                return (toMxBmina(res), Disable(res))
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '计量单位列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    // 进入详情
    jumpMateriel(ev) {
      const FNUMBER = ev.funitid
      this.$router.push({ path: `/editMeasuring/${FNUMBER}` })
    },
    // 搜索物料
    searchMaterialList(ev) {
      this.pagination.pageNum = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.customHandle(ev)
        this.getMaterialList(ev.detail)
      } else {
        this.getMaterialList()
      }
    },
    // 树形筛选
    async handleNodeClick(data) {
      this.currentNodeKey = data.funitgroupid
      this.getMaterialList()
    },
    // 获取物料数据
    async getMaterialList(ev) {
      this.details = []
      if (ev && !ev.page) {
        this.details = ev
      }
      const DATA = {
        ...this.pagination,
        search: this.searCollData.concat(this.details),
        funitgroupid: this.currentNodeKey
      }
      const { data: RES, code, message } = await queryUnitList(DATA)
      if (code === 1) {
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          type: 'error'
        })
        return
      }
      this.materialTableData = RES.array.map(res => {
        return toMxBmina(res)
      })
      this.total = RES.total
    },
    // 获取树型控件数据
    async getMaterialGroupL() {
      const { data: RES } = await queryUnitGroupList({})
      this.materialGroupL[0].details = RES.array
    },
    // 新增物料
    addMateril() {
      this.$router.push({ path: '/createMeasuring' })
    },
    // 查询物料
    detailMateriel(FNUMBER) {
      this.$router.push({ path: `/editMeasuring/${FNUMBER}` })
    },
    // 提交
    async materSub(ev) {
      const api = ev === 1 ? unitsSubmit : unitsUnSubmit
      this.toExamineFun(api)
    },
    // 审核
    async auditer(ev) {
      const api = ev === 1 ? unitsAudit : unitsUnAudit
      this.toExamineFun(api)
    },
    // 禁用反禁用
    async using(ev) {
      const api = ev === 1 ? unitsDisable : unitsUnDisable
      this.toExamineFun(api)
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: this.selectFbi }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.selectFbi = []
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
        this.getMaterialList()
      })
    },
    // 多选
    selectionData(val) {
      this.delArr = []
      this.selectFbi = []
      this.val = val
      this.val.forEach(res => {
        res.fnumber && this.selectFbi.push(res.fnumber)
        this.delArr.push({ fmaterialId: res.fmaterialId })
      })
    },
    // 删除物料
    deleteMater() {
      this.$confirm('确定要删除么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        const api = deleteUnits
        this.toExamineFun(api)
      })
    },
    // 自定义列表
    customHandle(ev) {
      this.tableHeaders = []
      if (ev.header) {
        ev.header.forEach(item => {
          this.tableHeader1.forEach(res => {
            if (res.label === item) {
              this.tableHeaders.push(res)
            }
          })
        })
        this.materialTableHeader = this.tableHeaders
      } else if (ev.fname === '缺省方案') {
        this.materialTableHeader = this.oldTabHeader
      } else {
        this.materialTableHeader = this.tableHeader1
      }
    }
  }
}
</script>

<style scoped lang="scss">
.mainPage {
  margin-top: 6px;
  display: flex;
  flex-direction: row;

  .left-mainPage {
    width: 12%;
    height: calc(100vh - 220px);
    overflow: auto;
    display: flex;
    flex-direction: column;
    border: 1px solid #ccc;
    &::-webkit-scrollbar-track-piece {
      background: #fff;
    }

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background: #eee;
      border-radius: 20px;
    }
  }
  .right-mainPage {
    width: 88%;
    margin-left: 10px;
  }
}
.materielList {
  @include listBom;
  display: flex;
  flex-direction: column;
  padding: 10px;
  background: #fff;
  .header {
    position: relative;
    .btn {
      transform: translateY(18%);
      margin-left: 450px !important;
    }
  }
  .productImg {
    width: auto;
    height: 40px;
  }
  .el-dialog .el-dialog__body {
    text-align: center;
  }
  .image {
    max-height: 600px;
    max-width: 600px;
  }
}
</style>
